import http.server
import socketserver
import os
import urllib.parse
import json
import tempfile
import shutil

# 端口设置
PORT = 8000

# 创建临时目录
TEMP_DIR = tempfile.gettempdir()

class CustomHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        # 健康检查接口
        if self.path == '/health':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            response = json.dumps({'status': 'healthy'}).encode()
            self.wfile.write(response)
            return
        
        # 静态文件服务
        # 处理根路径请求index.html
        if self.path == '/' or self.path == '/index.html':
            file_path = 'index.html'
        else:
            # 对于其他路径，尝试直接提供文件
            file_path = self.path[1:]  # 去掉开头的'/'
        
        try:
            # 检查文件是否存在
            if os.path.exists(file_path) and os.path.isfile(file_path):
                # 确定MIME类型
                if file_path.endswith('.html'):
                    mime_type = 'text/html'
                elif file_path.endswith('.css'):
                    mime_type = 'text/css'
                elif file_path.endswith('.js'):
                    mime_type = 'application/javascript'
                elif file_path.endswith('.json'):
                    mime_type = 'application/json'
                else:
                    mime_type = 'application/octet-stream'
                
                # 发送文件
                self.send_response(200)
                self.send_header('Content-Type', mime_type)
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                with open(file_path, 'rb') as file:
                    self.wfile.write(file.read())
            else:
                # 文件不存在
                self.send_response(404)
                self.send_header('Content-Type', 'text/plain')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                self.wfile.write(b'File not found')
        except Exception as e:
            # 发生错误
            self.send_response(500)
            self.send_header('Content-Type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            error_message = f'Error: {str(e)}'.encode()
            self.wfile.write(error_message)
    
    def do_POST(self):
        # 处理PDF转Word请求
        if self.path == '/api/pdf-to-word':
            content_length = int(self.headers['Content-Length'])
            boundary = self.headers['Content-Type'].split('boundary=')[1].encode()
            
            # 读取请求体
            data = self.rfile.read(content_length)
            
            try:
                # 解析multipart/form-data
                # 找到文件部分
                parts = data.split(boundary)
                file_part = None
                filename = None
                
                for part in parts:
                    if b'Content-Disposition: form-data' in part:
                        # 提取文件名
                        if b'filename=' in part:
                            filename_match = part.split(b'filename=')[1].split(b'"')[1]
                            filename = filename_match.decode('utf-8')
                            file_part = part
                            break
                
                if not filename or not file_part:
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    response = json.dumps({'error': '没有提供文件'}).encode()
                    self.wfile.write(response)
                    return
                
                # 检查文件扩展名
                if not filename.lower().endswith('.pdf'):
                    self.send_response(400)
                    self.send_header('Content-Type', 'application/json')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    response = json.dumps({'error': '只支持PDF文件'}).encode()
                    self.wfile.write(response)
                    return
                
                # 提取文件内容
                # 找到Content-Type后的空行
                content_start = file_part.find(b'\r\n\r\n') + 4
                content_end = file_part.rfind(b'\r\n')
                file_content = file_part[content_start:content_end]
                
                # 创建临时PDF文件
                temp_pdf_path = os.path.join(TEMP_DIR, f'temp_{os.getpid()}.pdf')
                with open(temp_pdf_path, 'wb') as f:
                    f.write(file_content)
                
                # 注意：由于环境限制，这里我们不进行实际的PDF转Word转换
                # 而是直接返回原始文件作为示例
                # 在实际环境中，应该使用pdf2docx等库进行转换
                
                # 生成输出文件名
                output_filename = os.path.splitext(filename)[0] + '.docx'
                
                # 发送响应
                self.send_response(200)
                self.send_header('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                self.send_header('Content-Disposition', f'attachment; filename="{output_filename}"')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                # 由于没有实际转换，这里简单地返回一个空的二进制数据
                # 在实际环境中，应该返回转换后的Word文件内容
                self.wfile.write(b'')
                
                # 清理临时文件
                try:
                    if os.path.exists(temp_pdf_path):
                        os.remove(temp_pdf_path)
                except:
                    pass
                    
            except Exception as e:
                # 发生错误
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                response = json.dumps({'error': f'处理请求时出错: {str(e)}'}).encode()
                self.wfile.write(response)
                
                # 清理临时文件
                try:
                    if 'temp_pdf_path' in locals() and os.path.exists(temp_pdf_path):
                        os.remove(temp_pdf_path)
                except:
                    pass
        else:
            # 不支持的POST路径
            self.send_response(404)
            self.send_header('Content-Type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(b'Not Found')
    
    def log_message(self, format, *args):
        # 禁用默认日志，避免过多输出
        return

# 启动服务器
def run_server():
    with socketserver.TCPServer(("0.0.0.0", PORT), CustomHandler) as httpd:
        print(f"服务器启动在 http://localhost:{PORT}")
        print("按 Ctrl+C 停止服务器")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务器已停止")
            httpd.server_close()

if __name__ == "__main__":
    run_server()